import qs from 'qs'

const BASE = require('~/config/index.js')
const TZY_SERVER_ENV = process.env.TZY_SERVER_ENV
export default function ({ $axios, redirect, app }) {
    // 设置基本URL
    if (process.server) {
        $axios.defaults.baseURL = BASE[TZY_SERVER_ENV].baseURL
    } else {
        $axios.defaults.baseURL = '/api'
    }
    $axios.interceptors.request.use(
        (config) => {
            if (config.method === 'get') {
                if (config.pathParams) {
                    config.url = `${config.url}/${config.data}`
                } else {
                    config.params = config.data
                }
            }
            if (
                config.method === 'post' &&
                config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8'
            ) {
                config.data = qs.stringify(config.data)
            }
            if (config.method === 'post' && config.headers['Content-Type'] === 'multipart/form-data') {
                const formData = new FormData()
                Object.keys(config.data).forEach((key) => {
                    formData.append(key, config.data[key])
                })
                config.data = formData
            }
            config.params = config.params || {}
            const userInfo = app.store.state.user.userInfo
            if (userInfo) {
                const { token, orgCategoryId, departmentId, companyId } = userInfo
                config.headers.Authorization = token ? 'Bearer ' + token : ''
                config.headers.orgCategoryId = orgCategoryId || 0
                config.headers.departmentId = departmentId || 0
                config.headers.companyId = companyId || 0
            }
            return config
        },
        (error) => {
            return Promise.reject(error)
        }
    )

    $axios.interceptors.response.use(
        (response) => {
            const result = response.data
            const code = result.code
            if (process.env.NODE_ENV === 'production') {
                if (code === 404) {
                    redirect('/404')
                }
            }
            return result
        },
        (error) => {
            return Promise.reject(error)
        }
    )
    $axios.onError((error) => {
        const code = parseInt(error.response && error.response.status)
        if (code === 400) {
            redirect('/404')
        } else if (code === 500) {
            redirect('/500')
        }
    })
}
